package com.example.springboot.config.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/5/24 14:31
 */
@Component
public class ZookeeperListener {
    private final CuratorFramework client;
    private NodeCache nodeCache;
    public static final String path = "/hello/world";
    @Autowired
    private JavaMailSenderImpl javaMailSender;

    public ZookeeperListener(CuratorFramework client) {
        this.client = client;
    }

    public void listen() {
        try {
            // 检查路径是否存在
            Stat stat = client.checkExists().forPath(path);
            if (stat == null) {
                // 创建节点
                client.create().creatingParentsIfNeeded().forPath(path);
                System.out.println("创建节点成功");
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        nodeCache = new NodeCache(client, path);
        // 添加监听路径改变后需要执行的任务
        nodeCache.getListenable().addListener(this::run);
        try {
            // 开始监听
            nodeCache.start();
            System.out.println("开始监听文件路径---" + path);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    private void run() {
        // 构建邮件消息
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom("1052031630@qq.com");
        // 设置收件人
        simpleMailMessage.setTo("528402297@qq.com");
        // 设置主题
        simpleMailMessage.setSubject("zookeeper路径变动");
        // 设置内容
        simpleMailMessage.setText(LocalDateTime.now() + "zookeeper文件路径" + path + "发生内容变动，请检查");
        javaMailSender.send(simpleMailMessage);
    }
}
